 package dlb.busstop.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import dlb.busstop.R;
import dlb.busstop.data.Bus;
import dlb.busstop.data.BusStop;

public class BusListViewAdapter extends BaseAdapter{

	private List<Bus> items = new ArrayList<Bus>();
	private LayoutInflater mLayoutInflater;
	
	public BusListViewAdapter(Activity activity) {
		mLayoutInflater = activity.getLayoutInflater();
	}
	
	public List<Bus> getList() {
		return items;
	}
	
	public void setList(List<Bus> items) {
		this.items = items;
		sortByTime();
	}
	
	public void clearItems(){
		items.clear();
		notifyDataSetChanged();
	}
	
	public void addItem(Bus item){
		items.add(item);
		sortByTime();
		notifyDataSetChanged();
	}
	
	public void removeItem(int position){
		items.remove(position);
		notifyDataSetChanged();
	}
	
	public void removeItem(BusStop item){
		items.remove(item);
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public Bus getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(convertView == null)
			convertView = mLayoutInflater.inflate(R.layout.layout_bus_list_item, parent,false);
		
		Bus currentObj = items.get(position);
		
		TextView number = (TextView) convertView.findViewById(R.id.tvBusNumber);
		TextView lastStop = (TextView) convertView.findViewById(R.id.tvBusLastStop);
		TextView time = (TextView) convertView.findViewById(R.id.tvBusTime);
		
		number.setText(currentObj.getNumber());
		lastStop.setText(currentObj.getLastStop());
		time.setText(currentObj.getTime());
		
		return convertView;
		
	}
	
	public void sortByTime(){
		Comparator<Bus> comparator = new Comparator<Bus>() {
			
			@Override
			public int compare(Bus lhs, Bus rhs) {
				int l = Integer.parseInt(lhs.getTime());
				int r = Integer.parseInt(rhs.getTime());
				
				if (l == r) {
					return 0;
				}
				if (l > r) {
					return 1;
				}
				return -1;
			}
		};
		Collections.sort(items, comparator);
		notifyDataSetChanged();
	}

	public void sortByNumber(final boolean asceding){
		Comparator<Bus> comparator = new Comparator<Bus>() {
			
			@Override
			public int compare(Bus lhs, Bus rhs) {
				int l = Integer.parseInt(lhs.getNumber());
				int r = Integer.parseInt(rhs.getNumber());
				if(r==l)
					return 0;
				if(asceding){
					return r > l ? 1 : -1;
				}
				return l > r ? 1  : -1;
			}
		};
		
		Collections.sort(items, comparator);
		notifyDataSetChanged();
	}
}
